<template>
  <el-dialog title="支付渠道绑定" :visible.sync="show" width="30%">
    <el-form :model="data" ref="form" label-width="150px">
      <!-- 微信 -->
      <template v-if="data.wechatPay">
        <div class="title">微信支付渠道</div>
        <el-form-item
          label="微信支付商户号"
          prop="wechatPay.payMchId"
          :rules="ruleRequired"
        >
          <el-input v-model="data.wechatPay.payMchId"></el-input>
        </el-form-item>
        <el-form-item
          label="微信支付手续费(%)"
          prop="wechatPay.charge"
          :verify="{ type: 'decimal', gte: 0, lte: 5 }"
        >
          <el-input v-model="data.wechatPay.charge"></el-input>
        </el-form-item>
        <el-form-item label="商户模式" prop="wechatPay.mchType">
          <el-select
            v-model="data.wechatPay.mchType"
            placeholder="请选择"
            :disabled="modelDisabled"
            style="width: 100%"
          >
            <el-option label="电商收付通模式" :value="2"></el-option>
            <el-option label="普通商户模式" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="data.wechatPay.mchType == 1">
          <el-card style="margin-bottom: 10px">
            <div slot="header" class="clearfix">
              <span>微信支付V2接口</span>
            </div>
            <el-form-item
              label="微信支付key"
              prop="wechatPay.payKey"
              :rules="ruleRequired"
            >
              <el-input v-model="data.wechatPay.payKey"></el-input>
            </el-form-item>
            <el-form-item
              label="证书文件"
              prop="wechatPay.p12CaPkFile"
              :rules="{ validator: P12fileValidator }"
            >
              <el-upload
                action="不自动上传"
                :auto-upload="false"
                :limit="1"
                :before-remove="beforeP12FileRemove"
                :on-change="P12fileChange"
                :on-exceed="handleExceed"
                :file-list="p12FileList"
                accept=".p12"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <span slot="tip">
                  <span class="ml15 c-grey">
                    上传文件不能超过{{ fileMaxSize }}MB
                  </span>
                  <el-tag
                    v-if="data.wechatPay.caP12Upload && fileList.length == 0"
                    size="small"
                    type="success"
                  >
                    已上传
                  </el-tag>
                </span>
              </el-upload>
            </el-form-item>
          </el-card>
          <el-card>
            <div slot="header" class="clearfix">
              <span>微信支付V3接口</span>
            </div>
            <el-form-item
              label="V3证书序列号"
              prop="wechatPay.mchSerialNo"
              :rules="ruleRequired"
            >
              <el-input v-model="data.wechatPay.mchSerialNo"></el-input>
            </el-form-item>
            <el-form-item
              label="APIV3密钥"
              prop="wechatPay.apiV3Key"
              :rules="ruleRequired"
            >
              <el-input v-model="data.wechatPay.apiV3Key"></el-input>
            </el-form-item>
            <el-form-item
              label="证书文件"
              prop="wechatPay.caPkFile"
              :rules="{ validator: fileValidator }"
            >
              <el-upload
                action="不自动上传"
                :auto-upload="false"
                :limit="1"
                :before-remove="beforeFileRemove"
                :on-change="fileChange"
                :on-exceed="handleExceed"
                :file-list="fileList"
                accept=".pem"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <span slot="tip">
                  <span class="ml15 c-grey">
                    上传文件不能超过{{ fileMaxSize }}MB
                  </span>
                  <el-tag
                    v-if="data.wechatPay.caUpload && fileList.length == 0"
                    size="small"
                    type="success"
                  >
                    已上传
                  </el-tag>
                </span>
              </el-upload>
            </el-form-item>
          </el-card>
        </template>
      </template>
    </el-form>
    <!-- {{ data }} -->
    <div class="floor">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="submit" v-loading="loading">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      id: '',
      show: false,
      disabled: false,
      loading: false,
      modelDisabled: false,
      fileMaxSize: 1, //MB
      pays: [],
      fileList: [],
      p12FileList: [],
      data: {},
      initData: {},
      wechatPay: {
        payMethod: 1,
        mchType: 2,
        charge: 0.6
      },
      ruleRequired: {
        required: true,
        message: '必填项'
      }
    }
  },
  watch: {
    show: {
      handler () {
        // 关闭重置
        if (!this.show) {
          this.disabled = false
          this.modelDisabled = false
          this.data.wechatPay = null
          this.data.alipay = null
          this.data = {}
          this.pays = []
          this.$refs['form'].clearValidate()
        }
      }
    },
    pays: {
      immediate: true,
      handler (newVal, onlVal) {
        let result = {
          mchId: this.id
        }
        for (let key of newVal) {
          result[key] = this.data[key] || this.initData[key]
        }
        this.data = result
      }
    }
  },
  methods: {
    async open (data) {
      this.id = data.merchantId
      // 查询详情
      let res = await this.$POST(
        '/sot-admin-api/merchant/merchant-pay/queryPayChannelByMchId',
        { id: this.id }
      )
      this.data = res.data

      this.data.wechatPay =
        this.data.wechatPay || this.$lo.cloneDeep(this.wechatPay)
      console.log(this.data)
      this.show = true
    },
    submit (status) {
      if (!this.data.wechatPay && !this.data.alipay) {
        this.$swal.warning('请先选择支付渠道')
        return
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          this.$POST(
            '/sot-admin-api/merchant/merchant-pay/bindPayChannel',
            this.getFormData()
          )
            .then(data => {
              this.loading = false
              this.show = false
              this.$emit('save')
            })
            .catch(err => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    getFormData () {
      let formData = new window.FormData()
      for (const key in this.data) {
        let item = this.data[key]
        if (item) {
          if (typeof item == 'object') {
            for (let key1 in item) {
              item[key1] && formData.append(`${key}.${key1}`, item[key1])
            }
          } else {
            item && formData.append(key, item)
          }
        }
        // if (this.data[key] != null) {
        //   //过滤掉 undefined 和 null
        //   formData.append(key, this.data[key]);
        // }
      }
      return formData
    },
    beforeFileRemove (file, fileList) {
      this.$set(this.data.wechatPay, 'caPkFile', null)
    },
    beforeP12FileRemove (file, fileList) {
      this.$set(this.data.wechatPay, 'p12CaPkFile', null)
    },
    fileChange (file) {
      if (this.data.wechatPay.caUpload) {
        this.$confirm('已存在上传的文件,是否覆盖?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            console.log(file.raw)

            this.$set(this.data.wechatPay, 'caPkFile', file.raw)
            this.$refs.form.validateField('caPkFile')
          })
          .catch(() => {
            this.fileList = []
          })
      } else {
        this.$set(this.data.wechatPay, 'caPkFile', file.raw)
        this.$refs.form.validateField('caPkFile')
      }
    },
    P12fileChange (file) {
      if (this.data.wechatPay.caP12Upload) {
        this.$confirm('已存在上传的文件,是否覆盖?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            console.log(file.raw)

            this.$set(this.data.wechatPay, 'p12CaPkFile', file.raw)
            this.$refs.form.validateField('p12CaPkFile')
          })
          .catch(() => {
            this.fileList = []
          })
      } else {
        this.$set(this.data.wechatPay, 'p12CaPkFile', file.raw)
        this.$refs.form.validateField('p12CaPkFile')
      }
    },
    handleExceed () {
      this.$swal.warning('最多只能上传一个文件')
    },
    fileValidator (rule, value, callback) {
      if (!this.data.wechatPay.caUpload && !this.data.wechatPay.caPkFile) {
        callback(new Error('请上传证书文件'))
      }
      if (value && value.size > this.fileMaxSize * 1024 * 1024) {
        callback(new Error(`上传文件不能超过${this.fileMaxSize}MB`))
        this.fileList = []
      } else {
        callback()
      }
    },
    P12fileValidator (rule, value, callback) {
      if (
        !this.data.wechatPay.caP12Upload &&
        !this.data.wechatPay.p12CaPkFile
      ) {
        callback(new Error('请上传证书文件'))
      }
      if (value && value.size > this.fileMaxSize * 1024 * 1024) {
        callback(new Error(`上传文件不能超过${this.fileMaxSize}MB`))
        this.fileList = []
      } else {
        callback()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  position: relative;
  margin: 0px 0 15px 20px;
  font-size: 17px;

  &::after {
    position: absolute;
    content: '';
    top: 1px;
    left: -15px;
    height: 15px;
    width: 5px;
    background: cornflowerblue;
  }
}

.floor {
  display: flex;
  justify-content: space-around;
  padding: 30px 150px;
}
</style>
